/**
 * User: 蕨菜
 * Date: 2019-05-22
 * Time: 16:17
 * Description: 此文件简要说明
 */

const {
    Student,
    Class,
    Grade
} = require('../../models');

const {
    AppUtil
} = require('../../util');

module.exports = async function addStudent(body, ctx) {

    const {
        name,
        phone,
        sex,
        studentId,
        father,
        fatherPhone,
        mother,
        motherPhone,
        address,
        active,
        gradeYear: year,
        classId,
    } = body;

    const studentInstance = await Student.create({
        name,
        phone,
        sex,
        studentId,
        father,
        fatherPhone,
        mother,
        motherPhone,
        address,
        active
    })

    if (!AppUtil.isEmpty(year)) {
        const gradeInstance = await Grade.findOne({
            where: {
                year
            }
        });
        gradeInstance.addStudent(studentInstance);
    }

    if (!AppUtil.isEmpty(classId)) {
        const classInstance = await Class.findByPk(classId);
        classInstance.addStudent(studentInstance);
    }

    const data = await Student.findByPk(studentInstance.id);
    return ctx.body = {
        success: true,
        data
    }

}